package cn.bdqn.controller;

import cn.bdqn.pojo.Right;
import cn.bdqn.pojo.Role;
import cn.bdqn.pojo.User;
import cn.bdqn.service.RightService;
import cn.bdqn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Resource
    UserService userService;
    @Resource
    RightService rightService;
    /**
     * 跳转登录页面
     *
     * @return
     */
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
        /**
         * 跳转首页
         * @return
         */
        @RequestMapping("/main")
        public String main(){
            return "main";
        }
        /**
         * 登录
         * @param usrName
         * @param usrPassword
         * @param model
         * @param session
         * @return
         */
        @RequestMapping(value = "/dologin")
        public String dologin (String usrName, String usrPassword,
                Model model, HttpSession session){
            //调用service方法，进行用户匹配
            User user = userService.login(usrName, usrPassword);
            //授权代码
            //获取用户的角色
            Role role=user.getRole();
            //查询角色所有权限
            List<Right> rights=rightService.findRightsByRoleId(role.getRoleId());
            role.getRights().addAll(rights);
            if (user != null) {//登录成功
            //放入session
                session.setAttribute("loginUser", user);
            //重定向到main方法
                return "redirect:/main";
            } else {
                //页面跳转（login.html）带提示信息--转发
                model.addAttribute("msg", "用户名或密码不正确");
                //转发到login.html
                return "login";
            }
        }
        /**
         * 退出
         * @param session
         * @return
         */
        @RequestMapping("/logout")
        public String logout (HttpSession session){
            session.removeAttribute("loginUser");
            return "login";
        }
    }


